/**

 * 
 */
package net.sapfree.fileUpload;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;

import com.google.gson.Gson;

import net.sapfree.common.Constants;
import net.sapfree.core.base.ServletBase;
import net.sapfree.core.web.RequestKit;

/**
 * @author Administrator
 * 
 */
public class FileUploadManagerServlet extends ServletBase
{
    private static final long serialVersionUID = 1L;
    
    /**
     * 日志管理
     */
    private static Log log =
        LogFactory.getFactory().getInstance(FileUploadManagerServlet.class);
    
    // 默认的执行方法
    protected void defaultAction(HttpServletRequest request,
        HttpServletResponse response)
    {
    }
    
    
    /**
     * 仅上传文件到磁盘目录
     * 
     * @param request
     * @param response
     */
    public void saveFile(HttpServletRequest request,
        HttpServletResponse response)
    {
        try
        {
            FileUploadManagerHandler uHandler = new FileUploadManagerHandler();
            Map<String, String[]> fileMap = uHandler.saveFile(request);
            
            Set<String> key_set = fileMap.keySet();
            ArrayList<UploadFile> files = new ArrayList<UploadFile>();
            for (String key : key_set)
            {
                UploadFile file = new UploadFile();
                
                String savepath = "", filenae = "";
                String[] strArr = fileMap.get(key);
                if (strArr != null && strArr.length == 2)
                {
                    savepath = strArr[0];
                    filenae = strArr[1];
                }
                file.setId(key);
                file.setSavePath(savepath);
                file.setSourceName(filenae);
                files.add(file);
            }
            
            Gson gson = new Gson();
            String json = gson.toJson(files);
            
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.write(json);
            pw.close();
        }
        catch (IOException e)
        {
            log.error("文件删除IOException:", e);
        }
    }
    
    
    
    /**
     * 上传照片
     * 
     * @param request
     * @param response
     */
    public void savePhoto(HttpServletRequest request,HttpServletResponse response)
    {
        try
        {
            FileUploadManagerHandler uHandler = new FileUploadManagerHandler();
            String[] strArr = uHandler.savePhoto(request);
            
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            
            String smallImgPath = strArr[2];
            
        	String serverJson = "{'fileName':'"+strArr[1]+"','imgPath':'"+strArr[0];
        	serverJson += "','smallImgPath':'"+smallImgPath+"'}";
        	
        	pw.write(serverJson);
            pw.close();
        }
        catch (IOException e)
        {
            log.error("文件删除IOException:", e);
        }
    }
    
    
    
    /**
     * 上传照片
     * 
     * @param request
     * @param response
     */
    public void saveImageOfArticle(HttpServletRequest request,HttpServletResponse response)
    {
        try
        {
            FileUploadManagerHandler uHandler = new FileUploadManagerHandler();
            String[] strArr = uHandler.saveImageOfArticle(request);
            
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            
            String path = request.getContextPath();
            
            JSONObject obj = new JSONObject();
    		obj.put("error", 0);
    		obj.put("url", path +"/servlet/FileUploadManagerServlet?method=articleImage&imgPath="+strArr[0]);
    		
    		pw.println(obj.toJSONString());
    		//out.println(obj.toJSONString());
        }
        catch (IOException e)
        {
            log.error("文件删除IOException:", e);
        }
    }
    
    
    
    /**
     * 显示图片
     * 
     * @param request
     * @param response
     */
    public void showImage(HttpServletRequest request,HttpServletResponse response)
    {
        	String GIF="image/gif;charset=GB2312";//设定输出的类型   
            String JPG="image/jpeg;charset=GB2312";
            String BMP="image/bmp;charset=GB2312";
            String TIFF="image/tiff;charset=GB2312";
            
            RequestKit kit=new RequestKit(request);
            
            String imagePath = kit.getParameter("imgPath","");
            String defPath = kit.getParameter("defPath","");
            
            if(imagePath.equals("")){
            	imagePath = Constants.DEFPHOTO_UPLOAD_PATH+File.separator+defPath;
            }else{
            	imagePath = Constants.PHOTO_UPLOAD_PATH+File.separator+imagePath;
            }
            
            OutputStream output;
			try {
				//得到输出流
				output = response.getOutputStream();
				
	            
	            	//不使用编码处理文件流的情况
				if(imagePath.toLowerCase().endsWith(".jpg"))
	            {
					response.setContentType(JPG);
	            }else if(imagePath.toLowerCase().endsWith(".gif")){
	            	response.setContentType(GIF);
	            }else if(imagePath.toLowerCase().endsWith(".bmp")){
	            	response.setContentType(BMP);
	            }else if(imagePath.toLowerCase().endsWith(".tif")){
	            	response.setContentType(TIFF);
	            }
	            	
	            	ServletContext context = getServletContext();
	            	//得到背景对象
	            	//InputStream imageIn=context.getResourceAsStream(imagePath);
	            	
	            	
	            	//文件流
	            	BufferedInputStream bis=new BufferedInputStream(new FileInputStream(new File(imagePath)));
	            	//输入缓冲流
	            	BufferedOutputStream bos=new BufferedOutputStream(output);
	            	//输出缓冲流
	            	byte data[]=new byte[4096];
	            	//缓冲字节数
	            	int size=0;
	            	size=bis.read(data);
	            	while (size!=-1){
	            		bos.write(data,0,size);
	            		size=bis.read(data);
	            	}
	            	bis.close();
	            	bos.flush();
	            	//清空输出缓冲流
	            	bos.close();
	            output.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
    
    
    
    
    /**
     * 显示文章中的图片
     * 
     * @param request
     * @param response
     */
    public void articleImage(HttpServletRequest request,HttpServletResponse response)
    {
        	String GIF="image/gif;charset=GB2312";//设定输出的类型   
            String JPG="image/jpeg;charset=GB2312";
            String BMP="image/bmp;charset=GB2312";
            String TIFF="image/tiff;charset=GB2312";
            
            RequestKit kit=new RequestKit(request);
            
            String imagePath = kit.getParameter("imgPath","");
            
            imagePath = Constants.ARTICLEIMAGE_UPLOAD_PATH+File.separator+imagePath;
            
            OutputStream output;
			try {
				//得到输出流
				output = response.getOutputStream();
				
	            
	            	//不使用编码处理文件流的情况
				if(imagePath.toLowerCase().endsWith(".jpg"))
	            {
					response.setContentType(JPG);
	            }else if(imagePath.toLowerCase().endsWith(".gif")){
	            	response.setContentType(GIF);
	            }else if(imagePath.toLowerCase().endsWith(".bmp")){
	            	response.setContentType(BMP);
	            }else if(imagePath.toLowerCase().endsWith(".tif")){
	            	response.setContentType(TIFF);
	            }
	            	
	            	ServletContext context = getServletContext();
	            	//得到背景对象
	            	//InputStream imageIn=context.getResourceAsStream(imagePath);
	            	
	            	
	            	//文件流
	            	BufferedInputStream bis=new BufferedInputStream(new FileInputStream(new File(imagePath)));
	            	//输入缓冲流
	            	BufferedOutputStream bos=new BufferedOutputStream(output);
	            	//输出缓冲流
	            	byte data[]=new byte[4096];
	            	//缓冲字节数
	            	int size=0;
	            	size=bis.read(data);
	            	while (size!=-1){
	            		bos.write(data,0,size);
	            		size=bis.read(data);
	            	}
	            	bis.close();
	            	bos.flush();
	            	//清空输出缓冲流
	            	bos.close();
	            output.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
    
    
    
    
    /**
     * 仅删除上传到磁盘的文件
     * 
     * @param request
     * @param response
     */
    public void delFile(HttpServletRequest request, HttpServletResponse response)
    {
        
        RequestKit kit = (RequestKit) request.getAttribute("RequestKit");
        String filePath = kit.getParameter("filePath", "");
        String realPath = Constants.FILE_UPLOAD_PATH;
        String sourcePath = realPath + File.separator + filePath;
        File sourceFile = new File(sourcePath);
        try
        {
            if (sourceFile.exists())
            {
                if (sourceFile.delete())
                {
                    this.appendString("文件删除成功.");
                }
                else
                {
                    this.appendString("文件删除失败.");
                }
            }
            else
            {
                this.appendString("指定文件不存在.");
            }
        }
        catch (IOException e)
        {
            log.error("文件删除IOException:", e);
        }
    }
    
    
    
    /**
     * 删除照片
     * 
     * @param request
     * @param response
     */
    public void delImage(HttpServletRequest request, HttpServletResponse response)
    {
        
        RequestKit kit = (RequestKit) request.getAttribute("RequestKit");
        String filePath = kit.getParameter("filePath", "");
        String realPath = Constants.PHOTO_UPLOAD_PATH;
        String sourcePath = realPath + File.separator + filePath;
        File sourceFile = new File(sourcePath);
        try
        {
            if (sourceFile.exists())
            {
                if (sourceFile.delete())
                {
                    this.appendString("文件删除成功.");
                }
                else
                {
                    this.appendString("文件删除失败.");
                }
            }
            else
            {
                this.appendString("指定文件不存在.");
            }
        }
        catch (IOException e)
        {
            log.error("文件删除IOException:", e);
        }
    }
    
    
    
    /**
     * 判断文件是否存在
     */
    public void isFileExist(HttpServletRequest request,
        HttpServletResponse response)
    {
        RequestKit kit = (RequestKit) request.getAttribute("RequestKit");
        String filePath = kit.getParameter("filePath", "");
        String realPath =Constants.FILE_UPLOAD_PATH;
        String sourcePath = realPath + File.separator + filePath;
        File sourceFile = new File(sourcePath);
        // 判断 文件夹是否存在，不存在则返回主界面
        if (filePath.length() == 0 || filePath.indexOf(".") < 0
            || !sourceFile.exists())
        {
            try
            {
                this.appendString("指定文件不存在.");
            }
            catch (IOException e)
            {
                log.error("查找指定文件IOException:", e);
            }
        }
    }
    
    /**
     * 下载Excel文件
     */
    public void fileDownLoad(HttpServletRequest request,
        HttpServletResponse response)
    {
        RequestKit kit = (RequestKit) request.getAttribute("RequestKit");
        String filePath = kit.getParameter("filePath", "");
        String fileName = kit.getParameter("fileName", "");
        
        InputStream fis = null;
        OutputStream toClient = null;
        
        String realPath = Constants.FILE_UPLOAD_PATH;
        
        String sourcePath = realPath + File.separator + filePath;
        File sourceFile = new File(sourcePath);
        // 判断 文件夹是否存在，不存在则返回主界面
        try
        {
            if (filePath.length() == 0 || filePath.indexOf(".") < 0
                || !sourceFile.exists())
            {
                appendString("<script>"
                    + "alert('下载文件异常.');window.history.go(-1)" + "</script>");
            }
            String strFileDisplayExt =
                fileName.substring(fileName.lastIndexOf(".") + 1);
            String strFileDownloadExt =
                filePath.substring(filePath.lastIndexOf(".") + 1);
            if (fileName.indexOf(".") < 0)
            {
                fileName += filePath.substring(filePath.lastIndexOf("."));
            }
            else if (!strFileDisplayExt.equalsIgnoreCase(strFileDownloadExt))
            {
                fileName += filePath.substring(filePath.lastIndexOf("."));
            }
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename="
                + new String(fileName.getBytes("gbk"), "ISO8859-1"));
            response.addHeader("Content-Length", "" + sourceFile.length());
            response.setContentType("application/octet-stream");
            // 以流的形式下载文件。
            fis = new BufferedInputStream(new FileInputStream(sourcePath));
            toClient = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[Constants.BUFFER_SIZE];
            int i = 0;
            while ((i = fis.read(buffer)) > 0)
            {
                toClient.write(buffer, 0, i);
            }
            toClient.flush();
        }
        catch (FileNotFoundException e)
        {
            log.error("文件下载FileNotFoundException:", e);
        }
        catch (IOException e)
        {
            log.error("文件下载IOException:", e);
        }
        finally
        {
            if (null != fis)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e)
                {
                    log.error("文件下载IOException:", e);
                }
            }
            if (null != toClient)
            {
                try
                {
                    toClient.close();
                }
                catch (IOException e)
                {
                    log.error("文件下载IOException:", e);
                }
            }
        }
    }
    
}
